import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, Clipboard, Image, TextInput } from 'react-native';
import { Container, Content, View, Toast, Text, Icon } from 'native-base';
import { ListItem, Avatar } from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import { connect } from 'react-redux';

import { Header, Loading, SmsCodeButton } from '../../component';
import { Colors, Metrics } from '../../theme';
import Http from '../../utils/HttpPost';
import ParamsValidate from '../../utils/ValueValidate';


class ChangePassword extends Component {
	constructor(props) {
		super(props);
		this._SendVcode = this._SendVcode.bind(this)
		this.state = {
			phone: '',
			oldPassword: '',
			smsCode: '',
			password: '',
			passwordAgain: '',
			isLoading: false,

			countryPickerVisible: false,
			countryCode: "86",
			contryCodeLabel: `中国大陆 +86`
		}
	}


	UNSAFE_componentWillMount() {

	}

	componentDidMount() {

	}

	/* 发送验证码 */
	_SendVcode(shouldStartCountting) {
		let phone = this.state.phone;
		// 手机号格式校验
		let msg = ParamsValidate('phone', phone);
		if (msg !== null){
		  Toast.show({
			text: msg,
			position: "top",
			textStyle: {textAlign: "center"},
			type: "warning"
		  })
		  setTimeout(() => { shouldStartCountting && shouldStartCountting(false) },0);
		  return;
		}

		Http('post',"/user/sendSms", {  
			phone, 
			purpose: 'general'
		}).then(res => {
			if (res.code === 200) {
				setTimeout(() => { shouldStartCountting && shouldStartCountting(true) }, 0);
				Toast.show({ text: "验证码已发送", position: "top", textStyle: { textAlign: "center" }, type: "success" });
			}else{
				setTimeout(() => { shouldStartCountting && shouldStartCountting(false) }, 0);
			}
		})
	}
	
	// 修改密码
	async submitFunc(){
		let { phone, smsCode, password, passwordAgain, oldPassword } = this.state;

		let phoneMsg = ParamsValidate('phone', phone);
		if (phoneMsg !== null) {
			Toast.show({
				text: phoneMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return;
		}

		let smsCodeMsg = ParamsValidate('smsCode', smsCode);
		if (smsCodeMsg !== null){
			Toast.show({
				text: smsCodeMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		let oldPasswordMsg = ParamsValidate('password', oldPassword);
		if (oldPasswordMsg !== null) {
			Toast.show({
				text: oldPasswordMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}
		
		let passwordMsg = ParamsValidate('password', password);
		if (passwordMsg !== null) {
			Toast.show({
				text: passwordMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		if (password != passwordAgain) {
			Toast.show({
				text: '两次密码输入不一致',
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		if (password == oldPassword) {
			Toast.show({
				text: '新密码与原密码相同,请修改',
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		this.setState({isLoading: true})
		Http('post',"/user/changePassword", {  
			phone, 
			smsCode, 
			oldPassword,
			password
		}).then(res => {
			this.setState({isLoading: false})
			if (res.code === 200) {
				Toast.show({ text: "密码修改成功！", textStyle: { textAlign: "center" }, type: "success" });
				this.props.navigation.navigate('Login'); 
			}
		})
	}

	render() {
		return (
			<Container>
				<Header title="修改密码" onLeftPress={() => this.props.navigation.goBack()} />
				<Loading showLoading={this.state.isLoading} />
				<Content padder>
					<TextInput
						inputStyle={Styles.inputText}
						placeholder='请输入手机号'
						keyboardType='phone-pad'
						// errorMessage='请输入正确的手机号码'
						value={this.state.phone}
						onChangeText={(value) => this.setState({ phone: value })}
					/>

					<View style={Styles.formItem}>
						<TextInput
							inputStyle={Styles.inputText}
							placeholder="请输入验证码"
							keyboardType='numeric'
							value={this.state.smsCode}
							onChangeText={(value) => this.setState({ smsCode: value })}
						/>
						<SmsCodeButton
							textStyle={{ color: 'white', fontSize: 12 }}
							style={{ }}
							buttonStyle={{}}
							timerCount={60}
							timerTitle={'获取验证码'}
							enable={this.state.phone.length == 11}
							onClick={
								(shouldStartCountting) => {
									this._SendVcode(shouldStartCountting)
								}}
							timerEnd={() => { this.setState({ state: '倒计时结束' }) }}
						/>
					</View>

					<TextInput
						inputStyle={Styles.inputText}
						placeholder="请输入原密码"
						secureTextEntry={true}
						onChangeText={(value) => this.setState({ oldPassword: value })}
					/>

					<TextInput
						inputStyle={Styles.inputText}
						placeholder="请输入新密码"
						secureTextEntry={true}
						onChangeText={(value) => this.setState({ password: value })}
					/>

					<TextInput
						inputStyle={Styles.inputText}
						placeholder="请再次确认新密码"
						// errorMessage='两次密码不一致'
						keyboardType="visible-password"
						secureTextEntry={true}
						onChangeText={(value) => this.setState({ passwordAgain: value })}
					/>

					<View style={Styles.signInView}>
						<TouchableOpacity onPress={() => this.submitFunc()} disabled={this.state.isLoading}>
							<LinearGradient style={[Styles.loginBtn]} colors={[Colors.subjectJbZuo, Colors.subject]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}>
								<Text style={{ fontSize: 14, padding: 12, color: Colors.bai }}>{`${this.state.isLoading ? "请求中..." : "修 改"}`}</Text>
							</LinearGradient>
						</TouchableOpacity>
					</View>
				</Content>
			</Container>
		);
	}

}

const mapStateToProps = state => ({
	logged: state.user.logged,
	token: state.user.token,

});

const mapDispatchToProps = dispatch => ({
	loginSuccess: userInfo => dispatch({ type: 'LoginSuccess', payload: { userInfo } }),
});

export default connect(mapStateToProps, mapDispatchToProps)(ChangePassword);

const Styles = StyleSheet.create({
	signInView: { marginTop: 58, alignItems: "center" },
	loginBtn: { width: Metrics.screenWidth * 0.6, alignItems: "center", borderRadius: 8 },
	resetPwd: { width: Metrics.screenWidth * 0.5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: 6 },
	inputText: { fontSize: 16, marginTop: 28, padding: 6,},
	showWelcome: { marginTop: 58, marginBottom: 28 },
	showWelcomeText: { textAlign: 'center', fontSize: 26 },
	yhXieyi: { fontSize: 12, color: Colors.hui99, textAlign: 'center', marginTop: 88 },
	yhXieyiText: { fontSize: 12, color: Colors.hui33, },
	formItem: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', },
});